/* Schema dependencies */

var Action = require('../schema/ActionSchema').ActionSchema,
    Game = require('../schema/GameSchema').GameSchema,
    Round = require('../schema/RoundSchema').RoundSchema,
    Gene = require('../schema/GeneSchema').GeneSchema;

/**
 * Finds all Actions that satisfy the given parameters.
 * See API documentation: GET /actions/
 *
 * @param req  {HTTP Request}  : HTTP GET request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON array of Action objects
 **/

exports.index = function(req, res) {
    var gameId  = req.params.game,
        roundId = gameId + "_" + req.params.round,
        query   = Game.findOne({id: gameId}).exclude('_id');

    // Limit query by range
    if (req.query.range) {
        query.limit(req.query.range);
    }

    query.exec(function(err, game) {
        // TODO: JSON error messages
        if (err) { 
            console.log(err); 
        } else {
            var i, rounds = game.rounds;
            for (i = 0; i < rounds.length; i++) {
                if (rounds[i].id == roundId) {
                    break;
                }
            }
            
            if (req.query.method == "hint") {
                res.json(rounds[i].actions.hints);
            } else if (req.query.method == "guess") {
                res.json(rounds[i].actions.guesses);
            } else {
                res.json({error: "missing method"});
            }
        }
    });
};

/**
 * Creates a Action object using the parameters found in the request body.
 * See API documentation: POST /actions/
 *
 * @param req  {HTTP Request}  : HTTP POST request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error
 **/

exports.create = function(req, res) {
    var id = Math.floor(Math.random() * 9000000) + 1000000,
        newAction = new Action(
        {
            id : req.params.game + "_" + req.params.round + "_" + id,
            value : req.body.value,
            type : req.body.type,
            time : new Date().toISOString()
        }
    );

    
    Game.findOne({id: req.params.game}, function(err, game) {
        var i, roundId = req.params.game + "_" + req.params.round;
        for (i = 0; i < game.rounds.length; i++) {
            if (game.rounds[i].id == roundId) {
                break;
            }
        }

        if (req.query.method == "hint") {
            game.rounds[i].actions.hints.push(newAction);
        } else if (req.query.method == "guess") {
            game.rounds[i].actions.guesses.push(newAction);
        } else {
            console.log('error');
        }
            
        game.save(function(err) {
            if (err) {
                console.log(err);
            } else {
                var returnBody = {
                    success : true,
                    id      : newAction.id,
                    code    : 100,
                    message : "Action successfully added to target Round."
                };
                res.json(returnBody);
            }
        });
    });
};

/**
 * Finds a single action object with the given action ID.
 * See API documentation: GET /actions/[id]
 *
 * @param req  {HTTP Request}  : HTTP GET request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error
 **/

exports.show = function(req, res) {
    var gameId  = req.params.game,
        roundId = gameId + "_" + req.params.round,
        actionId = roundId + "_" + req.params.action,
        query   = Game.findOne({id: gameId}).exclude('_id');
    
    query.exec(function(err, game) {
        // TODO: JSON error messages
        if (err) {
            console.log(err);
        } else {
            var i, j, actions, rounds = game.rounds;
            for (i = 0; i < rounds.length; i++) {
                if (rounds[i].id == roundId) {
                    break;
                }
            }
            
            if (req.query.method == "hint") {
                actions = game.rounds[i].actions.hints;
            } else if (req.query.method == "guess") {
                actions = game.rounds[i].actions.guesses;
            }

            for (j = 0; j < actions.length; j++) {
                if (actions[j].id == actionId) {
                    break;
                }
            }

            res.json(actions[j]);
        }
    });
};

/**
 * Updates a single Action object with the given action ID.
 * Accepts partial representations of the Action object.
 * See API documentation: PUT /actions/[id]
 *
 * @param req  {HTTP Request}  : HTTP PUT request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error.
 **/

exports.update = function(req, res) {
    var id = req.params.game + "_" + req.params.round + "_" + req.params.action,
        updatedDoc = {};

    if (req.body.value) { updatedDoc.value = req.body.value; }
    if (req.body.type) { updatedDoc.type = req.body.type; }

    Action.update({id: id}, updatedDoc, function(err) {
        if (err) {
            // TODO: JSON error messages
            console.log(err);
        } else {
            var returnBody = {
                success : true,
                code    : 200,
                message : "Action successfully updated in the database."
            };
            res.json(returnBody);
        }
    });
};

/**
 * Deletes a single Action object with the given action ID.
 * See API documentation: DELETE /actions/[id]
 *
 * @param req  {HTTP Request}  : HTTP DELETE request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP Response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error.
 **/

exports.destroy = function(req, res) {
    var roundId  = req.params.game + "_" + req.params.round;
    var actionId = roundId  + "_" + req.params.action;
    Round.findOne({id: roundId}, function(err, round) {
        var i, actions;
        
        if (req.query.method == "hint") {
            actions = round.actions.hints;
        } else if (req.query.method == "guess") {
            actions = round.actions.guesses;
        } else {
            console.log('error');
        }

        for (i = 0; i < actions.length; i++) {
            if (actions[i].id == actionId) {
                if (req.query.method == "hint") {
                    round.actions.hints[i].remove();
                } else if (req.query.method == "guess") {
                    round.actions.guesses[i].remove();
                }
                round.save(function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        var returnBody = {
                            success : true,
                            code    : 300,
                            message : "Action successfully deleted from the database."
                        };
                        res.json(returnBody);
                    }
                });
                break;
            }
        }
    });
};
